package com.hj.ct.fragment;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.hj.ct.R;
import com.hj.ct.activity.LoginActivity;
import com.hj.ct.activity.MainActivity;
import com.hj.ct.activity.TableActivity;
import com.hj.ct.adapter.DeviceListAdapter;
import com.hj.ct.logic.LogicActions;
import com.hj.ct.model.CompositeData;

public class DeviceListFragment extends BaseFragment {
	private View rootView;
	private ListView listView;
	private DeviceListAdapter adapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_device_list, null);
		initView();
		return rootView;
	}

	public View findViewById(int id) {
		return rootView.findViewById(id);
	}

	public void initView() {
		findViewById(R.id.btn_map_model).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				((MainActivity) getActivity()).changeDeviceMapModel();
			}
		});

		listView = (ListView) findViewById(R.id.listview_device);
	}

	private void initData(List<CompositeData> datas) {
		adapter = new DeviceListAdapter(getActivity());
		adapter.setDatas(datas);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(), TableActivity.class);
				intent.putExtra("data", adapter.getItem(position));
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});

	}

	public void handlerUI(int action, int code, Object... obj) {
		if (action == LogicActions.REAL_DATA_SUCCESS) {
			List<CompositeData> datas = (List<CompositeData>) obj[0];
			initData(datas);
		} else if (action == LogicActions.NEED_TO_LOGIN) {
			showReLoginDialog();
		}
	}

}
